package main

import (
    "../detector"
    "gopkg.in/alecthomas/kingpin.v2"
    "../common"
    "../pb"
    "fmt"
    "net"
    "google.golang.org/grpc"
)

var (
    zkAddr   = kingpin.Flag("zk", "database name").Strings()
    zkPath   = kingpin.Flag("metapath", "meta path").String()
    node     = kingpin.Flag("node", "node").String()
)


//./detector_rep_test  --zk="127.0.0.1:2181" --node="127.0.0.1:3001" --metapath="/meta"
func main() {
    kingpin.Parse()
    zkOpt := detector.ZkOption{
        ZkAddresses:                 *zkAddr,
        ZkMetaPath:                  *zkPath,
        ZkTimeoutMilliseconds:       3000,
        ZkCheckIntervalMilliseconds: 1000,
    }
    opt := detector.Option{
        BeaconIntervalMilliseconds: 100,
        CheckIntervalMilliseconds:  100,
        LeaseMilliseconds:          200,
        DelayMilliseconds:          120,
        GraceMilliseconds:          150,
    }
    srv := detector.NewFailureDetectorService(common.Node(*node), opt,
        func(a common.Node) { fmt.Printf("onConnectedCallback %v\n", a) },
        func(a []common.Node) { fmt.Printf("onDisconnectedCallback %v\n", a) })
    go srv.Start()
    defer srv.Stop()
    
    fd:=detector.NewZkDetectorOnRep(common.Node(*node),zkOpt,
        func() { fmt.Printf("meta loss \n") },
        func(a common.Node) { fmt.Printf("meta change to %v\n", a) })
    go fd.Start()
    defer fd.Stop()
    
    lis, err := net.Listen("tcp", *node)
    if err != nil {
        fmt.Printf("failed to listen: %v , err %v\n", *node, err)
        return
    }
    grpcServer := grpc.NewServer()
    pb.RegisterFailureDetectorServer(grpcServer, srv)
    grpcServer.Serve(lis)
    
}
